#!/usr/bin/env python
# yongming.li 
import sys
import os
import Image

def parsepng_2(filename):
    print 'filename is :' , filename
    R, G, B ,A = 0, 1, 2,3
    im =Image.open(filename)
    imageW = im.size[0]
    imageH = im.size[1]
    print im.format , im.size , im.mode

    myleft=10000
    myright=0
    mytop=10000
    mybottom=0
    mywidth =0 
    myheigth = 0
    i = 0
    for y in range(0, imageH):
        for x in range(0, imageW):
            offset = y*imageW + x
            xy = (x, y)
            rgba = im.getpixel(xy)
            #print rgba
            # (255, 240, 0, 255)
            if rgba[R] == 255  and rgba[G] == 255 \
                and rgba[B] == 255  and  rgba[A] == 0: 
                continue
            else:
                if x <= myleft :
                    myleft =x
                if x >= myright :
                    myright =x
                if y <= mytop :
                    mytop = y
                if y >= mybottom :
                    mybottom = y
    # laoguo you can modified here begin
    #myleft = myleft - 1
    #mytop = mytop - 1
    #myright = myright +1
    #mybottom = mybottom +1
    # laoguo you can modified here end

    print  myleft , myright , mytop  ,  mybottom
    mywidth = myright - myleft +1
    myheigth =  mybottom - mytop+1
    print mywidth , myheigth
    outim=Image.new("RGBA", (mywidth,myheigth))
    for y in range(0, myheigth):
        for x in range(0, mywidth):
            xy = (x, y)
            xyorigin = (x+myleft, y+mytop)
            rgbaorigin = im.getpixel(xyorigin)
            outim.putpixel(xy,rgbaorigin)
    
    outim.save('./out/%s'%(filename),)
    os.system('echo %d , %d , // %s >> ./out/results.txt'%(myleft,mytop,filename))



os.system('mkdir  ./out')
os.system('rm -rf  ./out/*')

pngfilelist = []
files = os.walk('./')
for pngfile in files:
    for item in pngfile:   
        for i in item:
            if 'png' in i:         
                pngfilelist.append(i)

os.system('echo "int imgIndex[ %d ] = {" >> ./out/results.txt'%(len(pngfilelist)))
for pngfile in pngfilelist:
    parsepng_2('%s'%(pngfile))  

os.system('echo "}; " >> ./out/results.txt')

